<?php

namespace App\Controller;

// +----------------------------------------------------------------------
// | 文件 AjaxTtableController.class.php
// +----------------------------------------------------------------------
// | 说明 
// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------
// | Author: 谢赤心 Legend. <xcx_legender@qq.com>
// +----------------------------------------------------------------------

class AjaxTtableController extends AjaxAppController
{
	/**
	 * @api {get} /App/AjaxTtable/getWinners  获取中奖名单
	 * @apiVersion 4.0.4
	 * @apiName getWinners
	 * @apiGroup AjaxTtable
	 *
	 * @apiParam {Number} id Table activity ID
	 *
	 * @apiSuccess {String} info  show message
	 * @apiSuccess {Number} status  status code.
	 * @apiSuccess {Object} data  extend datas.
	 *
	 * @apiSuccessExample Success-Response:
	 *	HTTP/1.1 200 OK
	 *     {
	 *			"data": "",
	 *			"info": "",
	 *			"status": 1,
	 *	}
	 *
	 * @apiError UserNotFound The id of the User was not found.
	 *
	 * @apiErrorExample Error-Response:
	 *	HTTP/1.1 200 OK
	 *		{
	 *			"status": "",
	 *			"info": "",
	 *			"data": "",
	 *		}
	 */
	public function getWinners($id = 0)
	{
		$service = service('MallActivityTurntable');
		$data    = $id ? $service->info($id) : $service->getLatest();
		$map = [
			'object_id' 	=> (int) $data['id'],
			'prize_level'	=> ['lt', 4]
		];
		$res = service('Mall/TurntableUserAction')->where($map)->order('create_time desc')->limit(20)->select();
		$Uevent = event('User');
		// print_r($res);
		foreach ($res as $key => $value) {
			$list[] = [
				'nickname' 	=> get_nickname($value['uid']),
				'mobile' 	=> substr_replace(get_username($value['uid']),'****', 3,4),
				'prize' 	=> $value['prize_level'],
			];
		}

		$this->jsonList($list);
	}	

	/**
	 * @api {get} /App/AjaxTtable/getWinners  获取中奖名单
	 * @apiVersion 4.0.4
	 * @apiName getWinners
	 * @apiGroup AjaxTtable
	 *
	 * @apiParam {Number} id Table activity ID
	 * @apiParam {String} appToken Users auth Token
	 *
	 * @apiSuccess {String} info  show message
	 * @apiSuccess {Number} status  status code.
	 * @apiSuccess {Object} data  extend datas.
	 *
	 * @apiSuccessExample Success-Response:
	 *	HTTP/1.1 200 OK
	 *     {
	 *			"data": "",
	 *			"info": "",
	 *			"status": 1,
	 *	}
	 *
	 * @apiError UserNotFound The id of the User was not found.
	 *
	 * @apiErrorExample Error-Response:
	 *	HTTP/1.1 200 OK
	 *		{
	 *			"status": "",
	 *			"info": "",
	 *			"data": "",
	 *		}
	 */
	public function info($id = 0, $appToken = '')
	{
		$service = service('MallActivityTurntable');
		$referral = I('referral', '', 'trim');
		$event = event('Activity');
		$data    = $id ? $service->info($id) : $service->getLatest();
		$event = event('Activity');
		$res = $event->checkStatus($this->service, $data);
		if (!$res)
		{
			return $this->showErr('该活动已经结束!');
		}

		$uid = $this->getUid($appToken);
		$this->uid = (int)$uid;
		if ($referral)
		{
			// 通过推广给用户加活动次数
			$event->userRefer($service, 'share', $data, $referral, $uid);
		}
		
		$times = 0;
		// 获取计算次数
		if ($uid)
		{
			$total_times = $event->getUserDailyTimes('MallActivityTurntable', $data, $uid);
			$times = $total_times - $this->getUserActionCount($data);
			$times = $times > 0 ? $times : 0;
		}
		
		// $ret['active'] = $data;
		$ret['times']  = $times;
		$ret['plus']   = $data['share_plus'];

		$noContactPrize = $this->getUserNoContact($data);
		if ($noContactPrize){
			$ret['prize'] = $noContactPrize['prize_level'];
			return $this->response(-1, $ret);
		} 

		$this->response(1, $ret);
		
	}

	/**
	 * @api {get} /App/AjaxTtable/action  开始抽奖
	 * @apiVersion 4.0.4
	 * @apiName action
	 * @apiGroup AjaxTtable
	 *
	 * @apiParam {Number} id Table activity ID
	 * @apiParam {String} appToken Users auth Token
	 *
	 * @apiSuccess {String} info  show message
	 * @apiSuccess {Number} status  status code.
	 * @apiSuccess {Object} data  extend datas.
	 *
	 * @apiSuccessExample Success-Response:
	 *	HTTP/1.1 200 OK
	 *     {
	 *			"data": "",
	 *			"info": "",
	 *			"status": 1,
	 *	}
	 *
	 * @apiError UserNotFound The id of the User was not found.
	 *
	 * @apiErrorExample Error-Response:
	 *	HTTP/1.1 200 OK
	 *		{
	 *			"status": "",
	 *			"info": "",
	 *			"data": "",
	 *		}
	 */
	public function action($id = 0, $appToken = '')
	{
		$this->checkUser($appToken);
		$service = service('MallActivityTurntable');
		$data    = $id ? $service->info($id) : $service->getLatest();
		$event = event('Activity');
		$res = $event->checkStatus($this->service, $data);
		if (!$res)
		{
			return $this->showErr('该活动已经结束!');
		}
		// 判断是否需要将之前的联系方式给出
		$noContactPrize = $this->getUserNoContact($data);
		if ($noContactPrize){
			return $this->showErrWithStatus(-1, '你上次的奖品还未填写联系信息, 请先填写');
		} 
		// 判断次数
		$total_times = $event->getUserDailyTimes($this->service, $data, $this->uid);
		$times = $total_times - $this->getUserActionCount($data);
		if ($times <= 0)
		{
			return $this->showErrWithStatus(-2, '您今日已经没有次数了, 请明日再来, 或分享获取更多次数');
		}

		// 获取抽奖结果
		$prize = $this->doAction($data);

		$action_id = $this->actionLog($data, $prize);
		$ret['prize'] = $prize;
		$ret['contact'] = in_array($prize, ['1', '2', '3']) ? 1 : 0;

		// 如果是4,5等奖则获取积分
		if (in_array($prize, [4,5]) )
		{
			$score = $prize == 4 ? 500 : 200;
			event('User')->score_oper($this->uid, $score, 'turntable', '轮盘抽奖', $data['id']);
		}

		return $this->response(1, $ret, 'ok');
			
	}

	/**
	 * @api {get} /App/AjaxTtable/contact  实物奖品填写地址
	 * @apiVersion 4.0.4
	 * @apiName contact
	 * @apiGroup AjaxTtable
	 *
	 * @apiParam {Number} id Table activity ID
	 * @apiParam {String} appToken Users auth Token
	 * @apiParam {String} name Users true name
	 * @apiParam {String} phone Users phone
	 * @apiParam {String} address Users address
	 *
	 * @apiSuccess {String} info  show message
	 * @apiSuccess {Number} status  status code.
	 * @apiSuccess {Object} data  extend datas.
	 *
	 * @apiSuccessExample Success-Response:
	 *	HTTP/1.1 200 OK
	 *     {
	 *			"data": "",
	 *			"info": "",
	 *			"status": 1,
	 *	}
	 *
	 * @apiError UserNotFound The id of the User was not found.
	 *
	 * @apiErrorExample Error-Response:
	 *	HTTP/1.1 200 OK
	 *		{
	 *			"status": "",
	 *			"info": "",
	 *			"data": "",
	 *		}
	 */
	public function contact($id = 0, $appToken = '')
	{
		$this->checkUser($appToken);
		$service = service('MallActivityTurntable');
		$data    = $id ? $service->info($id) : $service->getLatest();
		$event = event('Activity');
		$res = $event->checkStatus($this->service, $data);
		if (!$res)
		{
			return $this->showErr('该活动已经结束!');
		}
		// 判断是否需要将之前的联系方式给出
		$noContactPrize = $this->getUserNoContact($data);
		if (!$noContactPrize){
			return $this->showErrWithStatus(-3, '你没有需要填写地址的中奖信息');
		} 
		$name 		= I('name', '', 'trim');
		$phone 		= I('phone', '', 'trim');
		$address 	= I('address', '', 'trim');

		if (!$name || !$phone || !$address) return $this->showErrWithStatus(-4, '请完善资料');
		$save['contact'] = compact('name', 'phone', 'address');
		$res = service('Mall/TurntableUserAction')->where(['id' => (int)$noContactPrize['id']])->save($save);
		if ($res)
		{
			return $this->response(1, '', '操作成功');
		}
		return $this->showErr('操作失败');
	}


	// 获取已经剩余的奖品数量
	protected function getPrizeLeftCount(&$data, $prize_level, $limit)
	{
		$map = [
			'object_id' 	=> (int) $data['id'],
			'prize_level'	=> (int) $prize_level,
		];
		$count = service('Mall/TurntableUserAction')->where($map)->count();
		return $limit - $count;
	}

	// 获取用户未填写联系方式的获奖信息
	protected function getUserNoContact(&$data)
	{
		$map = [
			'object_id' 	=> (int) $data['id'],
			'prize_level'	=> ['$in' => [1,2,3]],
			'uid'			=> (int) $this->uid,
			'contact'		=> 0,
		];
		return service('Mall/TurntableUserAction')->where($map)->find();
	}

	// 记录用户抽奖行为
	protected function actionLog(&$data, $prize)
	{
		$save = [
			'uid' 			=> (int) $this->uid,
			'create_time' 	=> NOW_TIME,
			'date'   		=> date('Y-m-d'),
			'object_id' 	=> (int) $data['id'],
			'prize_level'	=> $prize,
			'contact'		=> 0,
		];
		$_id = service('Mall/TurntableUserAction')->add($save);
		// $map = ['_id' => new \MongoId($_id)];
		// $data = service('Mall/TurntableUserAction')->where($map)->find();
		return $_id;
	}

	// 获取用户当日的使用次数
	protected function getUserActionCount(&$data)
	{
		$map = [
			'uid' 			=> (int) $this->uid,
			'date'   		=> date('Y-m-d'),
			'object_id' 	=> (int) $data['id'],
		];
		return service('Mall/TurntableUserAction')->where($map)->count();
	}

	// 计算获得的奖品
	protected function doAction(&$data)
	{
		$temp_rates = 0;
		$prize_rates = [];

		$res = explode("\r\n", $data['prize']);
		foreach ($res as $key => $prize) {
			$level = $key + 1;
			list($rate, $limits) = explode("|", $prize);
			if ($limits)
			{
				list($key, $limit) = explode("=", $limits);
				if ($limit > 0)
				{
					$left = $this->getPrizeLeftCount($data, $level, $limit);
					if ($left <= 0) $rate = 0;
				}
			}
			$prize_rates[$level.'p'] = $rate;
			$temp_rates += $rate;
		}
		$prize_rates['6p'] = 1 - $temp_rates;
		$prize_bingo = mt_rand() / mt_getrandmax();
		
		$getPrize = '6p';

		$rate_ranger = 0;
		foreach ($prize_rates as $key => $value) {
			$rate_ranger += $value;
			if ($prize_bingo <= $rate_ranger) { $getPrize = $key; break;}
		}

		return intval($getPrize);
	}

}